package com.eascs.admin.o2o.internal.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.controller.BaseMasterViewController;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.o2o.internal.form.PayMentSearchForm;
import com.eascs.admin.o2o.internal.service.PayMentService;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.brand.service.O2oPartnerService;
import com.eascs.common.doc.excel.DefaultRowWriteHandler;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.file.FileTypeConstants;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxConfirmButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.tag.MenuTag;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.form.ZXPTCWForm;

/**
 * 
 * @author ycz 货款查询
 *
 */
@Controller
@RequestMapping("/payment")
public class PayMentViewController extends BaseMasterViewController {
	private static Logger log = LoggerFactory.getLogger(PayMentViewController.class);
	@Autowired
	private PayMentService payMentService;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Reference
	private WorkFlowService workFlowService;
	@Reference
	private ICustomerInfoService iCustomerInfoService;
	@Autowired
	private O2oPartnerService o2oPartnerService;
	@Value("${oa.O2OstampUseRequestSavePre.url}")
	private String O2OstampUseRequestSavePre;
	@Reference
	SysOrgService sysOrgService;
	@Override
	public void preHandle() {
		super.preHandle();
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "QueryLoadMenu");
	}

	/**
	 * @Description:
	 *               <p>
	 *               贷款管理
	 *               </p>
	 */
	@RequestMapping(value="/index",method=RequestMethod.GET)
	public String search(PayMentSearchForm payMentForm) {
		List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		ViewContext.put("ActOrgEntitys", orgProvince);
		payMentForm.setPageSize(BaseUtils.PAGE_SIZE);
		payMentForm.setPartnerId(getParatnerId(payMentForm.getPartnerName(), payMentForm.getBrandName()));
		
		List<User> users=sysOrgService.checkDataPermission(UserHolder.getUser().getNo());
		String no="";
		if (users!=null) {
			for (User user : users) {
				no+=user.getNo()+",";
			}
		}
		if (!"".equals(no)) {
			if (",".equals(no.substring(no.length()-1, no.length()))) {
				no=no.substring(0, no.length()-1);
			}
		}
		log.info("userno={}", no);
		payMentForm.setUsersno(no);
		
		PageResult<Object[]> pageResult = payMentService.findByPage(payMentForm);
		String[] titles = {"贷款单号", "征信银行", "借款人姓名", "信贷经理", "经营平台","省区", "贷款类型", "申请状态", "缴纳状态", "金额(万元)                  ",
			"创建时间" };
		SelectDataOption[] selectDataOptions = {null, new SelectDataOption("BANKTYPEO2O"),  null, null,null,null, new SelectDataOption("OTO_LOAN_TYPE"),
				new SelectDataOption("SQZT","ALL"), new SelectDataOption("OTO_BZJ_GLF"), null, new SelectDataOption("OTOREFUNDBILLSTATUS")
				};
		//new SelectDataOption("PLACEONFILE") 归挡状态
		// UrlUtil.resetParam(RequestContext.getRequestUrlWithQueryString(),
					// "pageOldIndex", "")
		StringBuffer pageUrl=new StringBuffer("/payment/index");
		StringBuffer reporto2ourl = new StringBuffer("/payment/download");
		if(payMentForm!=null){
			String billCode=payMentForm.getBillCode()==null?"":payMentForm.getBillCode();
			String loadName=payMentForm.getLoadName()==null?"":payMentForm.getLoadName();
			String userSurname=payMentForm.getUserSurname()==null?"":payMentForm.getUserSurname();
			String operatorName=payMentForm.getOperatorName()==null?"":payMentForm.getOperatorName();
			String payMentStatus=payMentForm.getPayMentStatus()==null?"":payMentForm.getPayMentStatus();
			String bankType=payMentForm.getBankType()==null?"":payMentForm.getBankType();
			String loanType=payMentForm.getLoanType()==null?"":payMentForm.getLoanType();
			String startTime=payMentForm.getStartTime()==null?"":payMentForm.getStartTime();
			String endTime=payMentForm.getEndTime()==null?"":payMentForm.getEndTime();
			String onPlace=payMentForm.getOnPlace()==null?"":payMentForm.getOnPlace();
			String buybackName=payMentForm.getBuybackName()==null?"":payMentForm.getBuybackName();
			String regionalName=payMentForm.getRegionalName()==null?"":payMentForm.getRegionalName();
			String brandName=payMentForm.getBrandName()==null?"":payMentForm.getBrandName();
			String partnerName=payMentForm.getPartnerName()==null?"":payMentForm.getPartnerName();
			String hostProvince=payMentForm.getHostProvince()==null?"":payMentForm.getHostProvince();
			String operationModel=payMentForm.getOperationModel()==null?"":payMentForm.getOperationModel();
			String bankloanname=payMentForm.getBankloanname()==null?"":payMentForm.getBankloanname();
			String otoBzjGlf=payMentForm.getOtoBzjGlf()==null?"":payMentForm.getOtoBzjGlf();
			pageUrl.append("?billCode="+billCode);
			pageUrl.append("&loadName="+loadName);
			pageUrl.append("&userSurname="+userSurname);
			pageUrl.append("&operatorName="+operatorName);
			pageUrl.append("&payMentStatus="+payMentStatus);
			pageUrl.append("&bankType="+bankType);
			pageUrl.append("&loanType="+loanType);
			pageUrl.append("&startTime="+startTime);
			pageUrl.append("&endTime="+endTime);
			pageUrl.append("&onPlace="+onPlace);
			pageUrl.append("&buybackName="+buybackName);
			pageUrl.append("&regionalName="+regionalName);
			pageUrl.append("&brandName="+brandName);
			pageUrl.append("&partnerName="+partnerName);
			pageUrl.append("&hostProvince="+hostProvince);
			pageUrl.append("&operationModel="+operationModel);
			pageUrl.append("&bankloanname="+bankloanname);
			pageUrl.append("&otoBzjGlf="+otoBzjGlf);
			
			reporto2ourl.append("?billCode="+billCode);
			reporto2ourl.append("&loadName="+loadName);
			reporto2ourl.append("&userSurname="+userSurname);
			reporto2ourl.append("&operatorName="+operatorName);
			reporto2ourl.append("&payMentStatus="+payMentStatus);
			reporto2ourl.append("&bankType="+bankType);
			reporto2ourl.append("&loanType="+loanType);
			reporto2ourl.append("&startTime="+startTime);
			reporto2ourl.append("&endTime="+endTime);
			reporto2ourl.append("&onPlace="+onPlace);	
			reporto2ourl.append("&buybackName="+buybackName);
			reporto2ourl.append("&regionalName="+regionalName);
			reporto2ourl.append("&brandName="+brandName);
			reporto2ourl.append("&partnerName="+partnerName);
			reporto2ourl.append("&hostProvince="+hostProvince);
			reporto2ourl.append("&operationModel="+operationModel);
			reporto2ourl.append("&bankloanname="+bankloanname);
			reporto2ourl.append("&otoBzjGlf="+otoBzjGlf);
			}
		pageUrl.append("&pageIndex=");
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, pageUrl.toString());
		paginationInfo.setSelectDataOptions(selectDataOptions);
		Button[] titleButton = new Button[] { ButtonHelper.createRedirectButton(null, "/detail?loanapplyNo=") };
		paginationInfo.setTitleButtons(titleButton);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFormats(new Format[]{null,null,null,null,null,null,null,null,null,new DecimalFormat(",###.00"), null, null});
		paginationInfo.setFirstRenderColumnIndex(1);
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("payMentForm", payMentForm);
		ViewContext.put("reporto2ourl", reporto2ourl.toString());
		User user = UserHolder.getUser();
		String accounturl=O2OstampUseRequestSavePre+"&user_name="+user.getAccount();
		ViewContext.put("O2OstampUseRequestSavePre1", accounturl);
		return "/payment/list";
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               贷款查询（征信岗）等
	 *               </p>
	 * @author LMX
	 * @date 2018年2月7日 下午2:33:32
	 */
	@RequestMapping(value="/zxgView",method=RequestMethod.GET)
	public String viewZXG(PayMentSearchForm payMentForm) {
		List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		ViewContext.put("ActOrgEntitys", orgProvince);
		payMentForm.setPageSize(BaseUtils.PAGE_SIZE);
		payMentForm.setPartnerId(getParatnerId(payMentForm.getPartnerName(), payMentForm.getBrandName()));
		payMentForm.setPayMentStatus("NEW,Z,ZF,N,NF,S");// 所有数据为未放款数据
		List<User> users=sysOrgService.checkDataPermission(UserHolder.getUser().getNo());
		String no="";
		if (users!=null) {
			for (User user : users) {
				no+=user.getNo()+",";
			}
		}
		if (!"".equals(no)) {
			if (",".equals(no.substring(no.length()-1, no.length()))) {
				no=no.substring(0, no.length()-1);
			}
		}
		log.info("userno={}", no);
		payMentForm.setUsersno(no);
		
		PageResult<Object[]> pageResult = payMentService.findByPage(payMentForm);
		String[] titles = {"贷款单号", "征信银行", "借款人姓名", "信贷经理", "经营平台","省区", "贷款类型", "申请状态", "缴纳状态", "金额(万元)","创建时间" };
		SelectDataOption[] selectDataOptions = {null, new SelectDataOption("BANKTYPEO2O"),  null, null,null,null, new SelectDataOption("OTO_LOAN_TYPE"),
				new SelectDataOption("SQZT","ALL"), new SelectDataOption("OTO_BZJ_GLF"), null, new SelectDataOption("OTOREFUNDBILLSTATUS")
		};
		
		StringBuffer pageUrl=new StringBuffer("/payment/zxgView");
		String billCode = null;
		String userMohuName = null;
		if (payMentForm != null) {
			billCode = payMentForm.getBillCode() == null ? "" : payMentForm.getBillCode();
			userMohuName = payMentForm.getUserMohuName() == null ? "" : payMentForm.getUserMohuName();//不能模糊查询
			pageUrl.append("?billCode=" + billCode);
			pageUrl.append("&userMohuName=" + userMohuName);
		}
		pageUrl.append("&pageIndex=");
//		pageUrl.append("&menutype="+payMentForm.getMenutype());
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, pageUrl.toString());
		paginationInfo.setSelectDataOptions(selectDataOptions);
		Button[] titleButton = new Button[] { ButtonHelper.createRedirectButton(null, "/detail?loanapplyNo=") };
		paginationInfo.setTitleButtons(titleButton);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFormats(new Format[] { null, null, null, null, null, null, null, null, null, new DecimalFormat(",###.00"), null, null });
		paginationInfo.setFirstRenderColumnIndex(1);
		String isDisplay = "none";
		if (StringUtil.isNotBlank(billCode) || StringUtil.isNotBlank(userMohuName)) {
			isDisplay = "";
		}
		ViewContext.put("isDisplay", isDisplay);//查询界面要输入查询条件才能查出列表
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("payMentForm", payMentForm);
		User user = UserHolder.getUser();
		String accounturl = O2OstampUseRequestSavePre + "&user_name=" + user.getAccount();
		ViewContext.put("O2OstampUseRequestSavePre1", accounturl);
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, payMentForm.getMenutype());
		return "/payment/list_zxgView";
	}


	/**
	 * @Description:
	 *               <p>
	 *               根据查询合作方name或者品牌name查询合作方id
	 *               </p>
	 * @author CXW
	 * @date 2017年2月16日 上午10:40:13
	 * @version V1.0
	 */
	public String getParatnerId(String partnerName, String brandName) {
		log.info("根据查询合作方name或者品牌name查询合作方id,partnerName={},brandName={}", partnerName, brandName);
		StringBuffer partnerIds = new StringBuffer();
		String partnerId = "";
		if (!StringUtils.isEmpty(partnerName) || !StringUtils.isEmpty(brandName)) {
			List<Object[]> data = o2oPartnerService.getPartnerIds(partnerName, brandName);
			if (data != null && data.size() > 0) {
				for (int i = 0; i < data.size(); i++) {
					for (int j = 0; j < data.get(i).length; j++) {
						partnerIds.append("'" + data.get(i)[j] + "',");
					}
				}
			} else {
				partnerId = "-1";
			}
		}
		if (partnerIds.length() > 0)
			partnerId = partnerIds.toString().substring(0, partnerIds.toString().length() - 1);
		return partnerId;
	}
	
	@RequestMapping(value="/contract",method=RequestMethod.GET)
	public String contract(@RequestParam("loanapplyNo")String loanapplyNo){
		O2oLoanapplyEntity loanapply = o2oLoanapplyService.findById(loanapplyNo);
		ViewContext.put("loan", loanapply);
		ViewContext.put("datalistInfo", getDatalistInfo(loanapplyNo));
		return "/detail/upload";
	}
	/**
	 * 补充内审附件
	 * @param zXPTCWForm
	 * @return
	 */
	@RequestMapping("/nsUpload")
	public String uploadNS(ZXPTCWForm zXPTCWForm) {
		O2oLoanapplyEntity loan = o2oLoanapplyService.findById(zXPTCWForm.getReferId());
		queryDataList(zXPTCWForm.getReferId(),FileTypeConstants.DALIST_TYPE_NSFJ);
		ViewContext.put("loan", loan);
		return "/detail/nsUpload";
	}
	/**
	 * 
	 * 工作流审批中补充附件表单
	 * 
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping("/upload")
	public String upload(ZXPTCWForm zXPTCWForm) {
		O2oLoanapplyEntity loan = o2oLoanapplyService.findById(zXPTCWForm.getReferId());
		ViewContext.put("datalistInfo", getDatalistInfo(zXPTCWForm.getReferId()));
		ViewContext.put("loan", loan);
		return "/detail/upload";
	}
	/**
	 * 
	 * 详情补充附件
	 * 
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping("/otherUpload")
	public String otherUpload(ZXPTCWForm zXPTCWForm) {
		O2oLoanapplyEntity loan = o2oLoanapplyService.findById(zXPTCWForm.getReferId());
		ViewContext.put("datalistInfo", getDatalistInfo(zXPTCWForm.getReferId()));
		ViewContext.put("loan", loan);
		return "/detail/otherUpload";
	}
	/**
	 * 附件列表
	 * @param loanapplyNo
	 * @return
	 */
	public PaginationInfo getDatalistInfo(String loanapplyNo){
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo);
		String titles[] = {"附件类型","文件名", "提交人", "提交时间","更新时间"};
		Button[] titleButtons = new Button[] {null,ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo datalistInfo = new PaginationInfo(pageResult, titles, "/loanUser/loanudpate");
		datalistInfo.setTitleButtons(titleButtons);
		datalistInfo.setBuildPagingNavigation(false);
		datalistInfo.setFirstRenderColumnIndex(1);
		datalistInfo.setBuildRowNumber(true);
		return datalistInfo;
	}
	/**
	 * 内审附件
	 * @param loanapplyNo
	 * @param code
	 * @param type
	 */
	public void queryDataList(String loanapplyNo, String code) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间"};
		Button[] titleButtons = new Button[] { null,
				ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		AjaxConfirmButton[] dealButton=null;
		dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
		paginationInfo.setMoreButtons(dealButton);
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("datalistInfo", paginationInfo);
	}
	
	
	@RequestMapping("/download")
	public void dowanload(PayMentSearchForm payMentForm,HttpServletResponse httpServletResponse, HttpServletRequest request) {
		payMentForm.setPageSize(Integer.MAX_VALUE);
		payMentForm.setPartnerId(getParatnerId(payMentForm.getPartnerName(), payMentForm.getBrandName()));
		PageResult<Object[]> pageResult = payMentService.findByPageExport(payMentForm);
		String path = PayMentViewController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/payment-model.xls").toString();
		OutputStream os = null;
		try {
			String outfile = "贷前数据.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			//httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
			ExcelApiHelper.writeHandle(os, PayMentViewController.class.getResourceAsStream("/excelTemplate/payment-model.xls"), defaultRowWriteHandler);
//			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
//			os.write(byteArrayOutputStream.toByteArray());
//			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}
	
}
